import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    appTitle: 'CN-Poetry',
    serviceItems: null,
    appItems: null,
    lang: {lang: 'ft'}, // 语言
    dataMsg: null, // 页面数据
    index_shi: 1 // 诗歌 当前第几首 索引
  },
  mutations: {
    setLang (state, lang) {
      state.lang = lang
    },
    setServiceItems (state, serviceItems) {
      state.serviceItems = serviceItems
    },
    setAppItems (state, appItems) {
      state.appItems = appItems
    },
    setDataMsg (state, dataMsg) {
      state.dataMsg = dataMsg
    }
  },
  actions: {
    changeLang ({commit}, lang) {
      commit('setLang', lang)
    },
    /**
     * Load service items from server, put results into storage.
     */
    loadServiceItems ({commit}) {
      Vue.prototype.$axios.get('/services')
        .then(response => {
          if (response.status === 200) {
            const serviceItems = response.data
            commit('setServiceItems', serviceItems)
          }
        })
    },
    /**
     * Load application items from server, put results into storage.
     */
    loadAppItems ({commit}) {
      Vue.prototype.$axios.get('/applications')
        .then(response => {
          if (response.status === 200) {
            const appItems = response.data
            commit('setAppItems', appItems)
          }
        })
    },
    loadDataMsg ({commit}, url) {
      Vue.prototype.$axios.get(this.state.lang.lang + url)
        .then(response => {
          if (response.status === 200) {
            const dataTemp = response.data
            commit('setDataMsg', dataTemp)
          }
        }).catch(error => {
          console.info('Error.' + error)
        })
    }
  },
  getters: {
    /**
     * Get service item arrays with filter
     */
    getServiceItems: (state) => (filter) => {
      return state.serviceItems.filter(e => {
        return (e || '').toLowerCase().indexOf((filter || '').toLowerCase()) > -1
      })
    },
    /**
     * Get application item arrays with filter
     */
    getAppItems: (state) => (filter) => {
      return state.appItems.filter(e => {
        return (e || '').toLowerCase().indexOf((filter || '').toLowerCase()) > -1
      })
    },
    dataMsg: (state) => {
      return state.dataMsg
    }
  }
})
